<template>
	<div>JS处理并行请求的四种方式</div>
</template>

<script>
	import {
		ref,
		reactive
	} from 'vue'
	export default {
		data() {
			return {}
		},
		mounted() {
			this.promiseAllTest();
			this.stateTest();
			this.yieldTest();
			this.asyncAwait();
		},

		methods: {
			//方法一 使用Promise.all
			promiseAllTest() {
				console.log('promiseAllTest')
				const startTime = new Date().getTime()

				function request(time) {
					return new Promise(resolve => {
						setTimeout(() => {
							resolve(time)
						}, time)
					})
				}
				let request1 = request(3000)
				let request2 = request(2000)
				Promise.all([request1, request2]).then(res => {
					console.log(res, new Date() - startTime) // [ 3000, 2000 ] 3001
				})
			},

			//方法二 自定义状态，在回调中判断返回状态，待2个请求都有返回值时再做处理
			stateTest() {
				console.log('stateTest')
				const startTime = new Date().getTime()

				function request(time) {
					return new Promise(resolve => {
						setTimeout(() => {
							resolve(time)
						}, time)
					})
				}
				let state = [undefined, undefined]
				let request1 = request(3000)
				let request2 = request(2000)
				console.log('request1',typeof request1,request1.__proto__)
				request1.then(res => {
					state[0] = res
					process()
				})
				request2.then(res => {
					state[1] = res
					process()
				})

				function process() {
					if (state[0] && state[1]) {
						console.log(state, new Date() - startTime) // [ 3000, 2000 ] 3001
					}
				}
			},
			
			//方法三 generator，yield
			yieldTest(){
				const startTime = new Date().getTime()
				function ajax(time, cb) {
				  setTimeout(() => cb(time), time)
				}
				function request(time) {
				  ajax(time, data => {
				    it.next(data);
				  })
				}
				function* main(){
					  let request1 = request(3000);
					  let request2 = request(2000);
					  let res1 = yield request1
					  let res2 = yield request2
						//这个地方有点问题，因为request2耗时较短，会先返回，也就是先执行it.next(2000)，导致res1获得了request2的返回值,res1=2000
					  console.log('yieldTest=',res1, res2, new Date() - startTime) // 2000 3000 3009
				}
				let it =main()
				it.next();
			},
			
			asyncAwait(){
				const startTime = new Date().getTime()
				function request (time) {
				  return new Promise(resolve => {
				    setTimeout(() => {
				      resolve(time)
				    }, time)
				  })
				}
				(async function(){
					let request1 = request(3000)
					let request2 = request(2000)
					let res1 = await request1
					let res2 = await request2
					console.log('asyncAwait=',res1, res2, new Date() - startTime) //3000 2000 3009
				})()
			},

		},

	}
</script>

<style>
</style>
